import React, { useEffect, useState, useMemo, Fragment } from 'react'
import {
  Row,
  Col,
  message,
  Skeleton,
  Button,
  Space
} from 'antd'
import {
  ProFormText,
  ProForm,
  ProFormTextArea,
  ProFormSelect,
  ProFormDependency,
  ProCard,
  CheckCard
} from '@ant-design/pro-components';
import { PlusOutlined } from '@ant-design/icons';
import {
  reqPatientList,
  reqDetal,
  reqUpdate,
  reqPulseUpdate,
  reqPulseDetail,
  reqPulseList,
  reqQuestionTermList,
  reqIllnessList
} from '@/services/basicConsultation';

import {
  reqPulseCalibrationList,
  reqTongueCalibrationList,
  reqDiagnosisTermList,
  reqDiagnosisTermListByGrade,
  reqSeniorInquiryList,
  reqSeniorInquiryUpdate,
  reqSymptomList,
  reqSymptomListByGrade,
  reqWesternMedicineList,
  reqBaseFormulaList,
  reqBaseFormulaDetailList,
  reqEtiologyCategoryList,
  reqEtiologyList,
  reqEtiologyCategoryListByDiagnosis,
  reqSeniorInquiryPrescriptionMedication,
  reqBaseFormulaDetailGetBaseFormulaHerb,
} from '@/services/firstConsultation';

import EditModal from './components/EditModal'

import styles from './index.module.less'

const Consultation = ({
  user,
  upDataInfo
}) => {
  const [formObj] = ProForm.useForm()

  const [data, setData] = useState<any>(null)
  const [messageList, setMessageList] = useState<any>(null)

  const [categoryList, setCategoryList] = useState<any>(null)

  const [selectList, setSelectList] = useState<any>(null)
  const [messageKeys, setMessage] = useState<any>([])



  // /api/v1/etiology/listAll
  // /api/v1/etiologyCategory/listAll
  const [initialValues, setinitialValues] = useState<any>(null)

  function arrayFormatOptions(array: []) {
    if (!Array.isArray(array)) return []
    return array.map((item: any) => ({
      label: item?.name,
      title: item?.name,
      value: item?.id,
      size: 'small',
    }))
  }



  function arrayFormatOptGroup(array: []) {
    if (!Array.isArray(array)) return []
    return array.map((item: any) => ({
      label: item?.parentDiagnosisTerm?.name,
      value: item?.parentDiagnosisTerm?.id,
      options: arrayFormatOptions(item?.diagnosisTermList)
    }))
  }

  // {
  //   label: 'Manager',
  //   options: [
  //     { label: 'Jack', value: 'jack' },
  //     { label: 'Lucy', value: 'lucy' },
  //   ],
  // },

  async function init() {
    try {
      const res = await reqDiagnosisTermListByGrade({})

      const res2 = await reqEtiologyList({})

      if (res2?.resultCode == '00000000') {
        setCategoryList(res2?.data)
      }

      console.log('诊断术语列表-分级信息 :>> ', res?.data);
      if (res?.resultCode == '00000000') {
        setData(res?.data)
      } else {
        message.error(`诊断术语列表-分级信息出错！${res?.message}`)
      }
    } catch (error: any) {
      message.error('诊断术语列表-分级信息出错！', error)
      console.log('诊断术语列表-分级信息出错！ :>> ', error);
    }
  }


  useEffect(() => {
    if (user?.id) {
      init()
    }
  }, [user])




  const [seletTyDiagnosisIds, setSeletTyDiagnosisIds] = useState([])


  async function getCheckCardList(tyDiagnosisIds: any) {
    const errLogName = '根据诊断术语信息查询病因'
    if (!tyDiagnosisIds?.length) return;
    try {
      const res = await reqEtiologyCategoryListByDiagnosis({
        tyDiagnosisIds
      })
      console.log(`${errLogName}信息 :>> `, res?.data);
      if (res?.resultCode == '00000000') {
        setMessageList(res?.data)
      } else {
        message.error(`${errLogName}信息出错！${res?.message}`)
      }
    } catch (error: any) {
      message.error(`${errLogName}信息出错！`, error)
      console.log(`${errLogName}信息出错！ :>> `, error);
    }
  }


  useEffect(() => {
    if (seletTyDiagnosisIds?.length > 0) {
      getCheckCardList(seletTyDiagnosisIds)
    }

  }, [seletTyDiagnosisIds])

  // console.log('categoryList :>> ',
  //   datamMpObj,
  //   messageKeys,
  //   selectList,
  //   categoryList,
  //   mapObj,
  //   data,
  //   seletTyDiagnosisIds
  // );


  const tyDiagnosisInfo = useMemo(() => {
    return user?.seniorInquiry?.tyDiagnosisTermJson && JSON.parse(user?.seniorInquiry?.tyDiagnosisTermJson);
  }, [user])
  const [isEdit, setIsEdit] = useState(tyDiagnosisInfo)


  useEffect(() => {
    if (tyDiagnosisInfo?.tyDiagnosisJson) {
      let arr: any = [];
      tyDiagnosisInfo?.tyDiagnosisJson?.map((item: any, index: number) => {
        item?.child?.map((li: any, i: number) => {
          arr.push(li?.id)
        })
      })
      console.log('tyDiagnosisInfo arr==== :>> ', arr);
      setSeletTyDiagnosisIds(arr)
    }
  }, [tyDiagnosisInfo?.tyDiagnosisJson])

  useEffect(() => {
    if (messageKeys?.length > 0) {
      setSelectList(messageKeys[messageKeys.length - 1])
    }
  }, [messageKeys])


  useEffect(() => {
    if (tyDiagnosisInfo?.messageJson) {
      let arr: any = [];
      tyDiagnosisInfo?.messageJson?.map((item: any) => {
        arr.push(item?.id)
      })
      setMessage(arr)
    }
  }, [tyDiagnosisInfo?.messageJson])

  useEffect(() => {
    if (user?.seniorInquiry?.doctorAdvice && isEdit && tyDiagnosisInfo) {
      formObj.setFieldValue('doctorAdvice', user?.seniorInquiry?.doctorAdvice);
    }
  }, [isEdit, user, tyDiagnosisInfo])


  // console.log('tyDiagnosisInfo =====:>> ', tyDiagnosisInfo, seletTyDiagnosisIds);
  if (tyDiagnosisInfo && isEdit) return (
    <ProCard split="horizontal">
      <ProCard>
        <div>
          <Space>
            <b>病因病机：</b>
            <div>
              {
                tyDiagnosisInfo?.messageJson?.map((item: any, index: number) => (
                  <span key={index}>{index != 0 && '、'}{item?.name}</span>
                ))
              }
            </div>
          </Space>
        </div>
        {
          tyDiagnosisInfo?.tyDiagnosisJson?.map((item: any, index: number) => (
            <div key={index}>
              <Space>
                <b>{item?.name}：</b>
                <div>
                  {
                    item?.child?.map((li: any, i: number) => (
                      <span key={i}>{i != 0 && '、'}{li?.name}</span>
                    ))
                  }
                </div>
              </Space>
            </div>
          ))
        }
      </ProCard>
      {/* <ProCard>
        <Button onClick={() => setIsEdit(false)}>编辑</Button>
      </ProCard> */}
    </ProCard>
  )

  return null;
  // return (
  //   <ProCard split="horizontal">
  //     {tyDiagnosisInfo && <Button danger onClick={onClose}>取消修改</Button>}
  //     <ProForm
  //       form={formObj}
  //       layout="horizontal"
  //       // initialValues={initialValues}
  //       onFinish={(values): Promise<any> => onFinish(values)}
  //     >
  //       <ProCard split="vertical">
  //         <ProCard title="病因" colSpan="62%">
  //           <div className={styles.checkCardWrap}>
  //             <CheckCard.Group
  //               multiple
  //               value={seletTyDiagnosisIds}
  //               onChange={onChangeCheckCard}
  //             >
  //               {
  //                 Array.isArray(data) &&
  //                 arrayFormatOptGroup(data).map((item, index) => {
  //                   return (
  //                     <div key={index} >
  //                       <h3>{item?.label}</h3>
  //                       {
  //                         item?.options?.map((li, i) => (
  //                           <CheckCard
  //                             className={styles.checkCard}
  //                             key={i}
  //                             title={li?.title}
  //                             value={li?.value}
  //                           />
  //                         ))
  //                       }
  //                     </div>
  //                   )
  //                 })
  //               }
  //             </CheckCard.Group>
  //           </div>
  //         </ProCard>
  //         <ProCard title="病因病机" className={styles.rightNoPadding}>
  //           <div>
  //             <div>
  //               {
  //                 isOpen &&
  //                 <EditModal
  //                   isOpen={isOpen}
  //                   categoryList={categoryList}
  //                   handleModal={handleModal}
  //                   defArr={messageKeys}
  //                 />
  //               }
  //               <div className={styles.selectBox}>
  //                 <h3>已选择：</h3>
  //                 <Button type='primary' onClick={() => handleModal(true)}>选择病因</Button>
  //               </div>

  //               <CheckCard.Group
  //                 value={selectList}
  //                 onChange={onChangeSelectList}
  //               >
  //                 {
  //                   messageKeys?.map((li: any, i: number) => (
  //                     <CheckCard
  //                       className={styles.checkCard}
  //                       key={i}
  //                       title={mapObj && mapObj[li] && mapObj[li]?.name}
  //                       value={li}
  //                     />
  //                   ))
  //                 }
  //               </CheckCard.Group>
  //             </div>
  //             <div>
  //               <h3>候选区：</h3>
  //               <CheckCard.Group
  //                 value={messageKeys}
  //                 multiple
  //                 onChange={onChangeCategoryList}
  //               >
  //                 {
  //                   messageList?.map((li: any, i: number) => (
  //                     <CheckCard
  //                       className={styles.checkCard}
  //                       key={i}
  //                       title={li?.name}
  //                       value={li?.id}
  //                     />
  //                   ))
  //                 }
  //               </CheckCard.Group>
  //             </div>
  //           </div>
  //           {
  //             textMessage &&
  //             (
  //               <div>
  //                 <h3>同义词：</h3>
  //                 <div>{textMessage?.name}</div>
  //                 <h3>概要：</h3>
  //                 <div>{textMessage?.summary}</div>
  //                 <h3>常见症状：</h3>
  //                 <div>{textMessage?.commonSymptom}</div>
  //                 <h3>治法治则：</h3>
  //                 <div>{textMessage?.ruleLaw}</div>
  //                 <h3>代表方药：</h3>
  //                 <div>{textMessage?.representingMedicine}</div>
  //               </div>
  //             )
  //           }
  //         </ProCard>
  //       </ProCard>
  //       <ProCard>
  //         <ProFormTextArea name="doctorAdvice" label="医生建议" placeholder="请输入您的建议..." />
  //       </ProCard>
  //     </ProForm>
  //   </ProCard>
  // )

}


export default Consultation;